package collectors.email.models;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;

import play.data.validation.Constraints.Email;
import play.data.validation.Constraints.Required;
import play.libs.F.Promise;
import play.libs.WS.Response;
import collectors.email.util.OAuthUtil;

@Entity
@DiscriminatorValue(value="gmail") 
public class GmailData extends EmailData {
	
	@Required 
	public String sub; //unique identifier across all google accounts for the user
	@Required @Email
	public String email;
	@Required
	public String accessToken;
	
	//TODO worry about this later
	/*
	@Required
	public String refreshToken;
	*/
	@Required
	public long expiresIn;
	@Required
	public long grantedAt;

	@Override
	public String toString() {
		return "GmailData [sub=" + sub + ", email=" + email + ", accessToken="
				+ accessToken + /*", refreshToken=" + refreshToken +*/
				", expiresIn=" + expiresIn + "]";
	}
	
	public static GmailData create(String sub, String email, String accessToken,
			long expires, long granted) {
		GmailData data = new GmailData();
		data.sub = sub;
		data.email = email;
		data.accessToken = accessToken;
		data.expiresIn = expires;
		data.grantedAt = granted;
		
		//unidirectional relationship -> we save it on YouUser
//		data.save();
		return data;
	}

	@Override
	public Promise<Response> unlink() {
		return OAuthUtil.revokeToken(accessToken);
	}
	
	@Override
	public boolean equals(Object e) {
		return e instanceof GmailData 
				&& ((GmailData) e).sub.equals(this.sub);
	}
}
